/**
 * 服务
 * 位置生成
 */
import config from "../config";

type positionType = { x: number, y: number }

class Position {
    // 集合包括砖墙、草地、砖块，都在里面
    collection: positionType[] = []

    public getPositionCollection(num: number) {
        const collection = [] as { x: number, y: number }[]
        for (let i = 0; i < num; i++) {
            let count = 0
            while (true) {
                const position = this.position()
                // 从整个集合中防止重叠坐标
                const exists = this.collection.some(item =>
                    item.x == position.x && item.y == position.y)
                if (!exists || count > 4000) {
                    collection.push(position)
                    this.collection.push(position)
                    break;
                }
                // 防止死循环
                count++;
            }
        }
        return collection
    }

    // 返回随机位置
    public position() {
        let x: number, y: number;
        let gridNumX = config.canvas.width / config.model.common.width;
        // 随机格子数量
        let leftNumX = Math.floor(Math.random() * gridNumX)
        //转换成px
        x = leftNumX * config.model.common.width


        let gridNumY = config.canvas.height / config.model.common.height;
        // 随机格子数量
        let leftNumY = Math.floor(Math.random() * (gridNumY - 4))
        //转换成px,且顶部空出一格
        y = (leftNumY + 1) * config.model.common.height
        return {x, y}
    }
}

export default new Position()
